<template>
  <div>
    <div class="uploadImg">
      <!-- el-upload 组件用于文件上传，action 属性留空因为我们将使用自定义上传方法 -->
      <!-- 使用自定义的 handleUpload 方法来处理上传 -->
      <!-- 给上传组件注册引用，可以通过 this.$refs.upload 访问 -->
      <!-- 绑定文件列表，显示已选择的文件 -->
      <!-- 绑定上传成功的回调 -->
      <!-- 设置为 false 以禁用自动上传，需手动点击上传按钮 -->
      <el-upload action="#" 
      :http-request="handleUpload"  
      ref="upload" :file-list="fileList"
        :on-success="uploadSuccess" :auto-upload="false">
        <el-button slot="trigger" size="small">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="primary" @click="submitUpload">上传</el-button>
      </el-upload>
    </div>
    <div class="imglist">
      <div class="img" v-for="img in imgList">
       <el-button 
              <el-button @click="flag(scope.row.id)" v-if="scope.row.flag === true" type="primary" size="small">禁用</el-button>
            <el-button @click="flag(scope.row.id)" v-else size="small">解禁</el-button>
            </el-button>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'index',
  components: {

  },
  mixins: [],
  props: {

  },
  data() {
    return {
      imgList: [],
      fileList: []
    }
  },
  mounted() {
    this.getImage()
  },
  methods: {
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleUpload(params) {
      const userinfo = JSON.parse(localStorage.getItem('userinfo'))

      const formdata = new FormData()
      formdata.append('id', userinfo.id)
      formdata.append('carousel', params.file)

      this.$http.post('carousel/backend/add', formdata, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        if (res.data.code === 1) {
          this.$message(res.data.message)
          this.getImage()
        } else {
          this.$message(res.data.message)
        }
      })
    },
    uploadSuccess(res) {
      this.getImage()
    },
    getImage() {
      this.$http.get('/carousel/list').then(res => {
        if (res.data.code === 1) {
          this.imgList = res.data.list
        }
      })
    },
    delImg(imgId) {
      const userinfo = JSON.parse(localStorage.getItem('userinfo'))
      this.$http.post('carousel/backend/remove', { id: userinfo.id, imgId: imgId }).then(res => {
        if (res.data.code === 1) {
          this.$message(res.data.message)// 显示成功消息
          this.getImage()// 重新获取图片列表
        } else {
          this.$message(res.data.message)// 显示失败消息
        }
      })
    }
  }
};
</script>
<style scoped>
.uploadImg {
  margin: 24px;
}

.imglist {
  width: 100%;
  display: flex;
  gap: 24px;
  flex-wrap: wrap;
  padding: 24px;
}

.img {
  position: relative;
}

.del {
  position: absolute;
  top: -10px;
  right: -10px;
}
</style>